package ExceptionDemo;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

public class BankService {
    private static final Logger logger = Logger.getLogger(BankService.class.getName());
    private Map<String, Double> accounts = new HashMap<>();

    public BankService() {
        // 初始化模拟账户
        accounts.put("A001", 1000.0);
        accounts.put("A002", 500.0);
    }

    public void transfer(String from, String to, double amount)
            throws InsufficientBalanceException, InvalidAmountException, AccountNotFoundException {

        if (amount <= 0) {
            logger.warning("Invalid transfer amount: " + amount);
            throw new InvalidAmountException("转账金额必须大于0: " + amount);
        }

        if (!accounts.containsKey(from) || !accounts.containsKey(to)) {
            logger.warning("Account not found. From: " + from + ", To: " + to);
            throw new AccountNotFoundException("账户不存在");
        }

        if (accounts.get(from) < amount) {
            logger.warning("Insufficient balance in account: " + from);
            throw new InsufficientBalanceException("余额不足");
        }

        logger.info("Transferring " + amount + " from " + from + " to " + to);

        // 模拟数据库操作
        try (DatabaseConnection conn = new DatabaseConnection()) {
            conn.transfer(from, to, amount);
            // 更新本地账户余额
            accounts.put(from, accounts.get(from) - amount);
            accounts.put(to, accounts.get(to) + amount);
        } catch (Exception e) {
            logger.severe("Database error during transfer: " + e.getMessage());
            // 使用异常链保留原始异常信息
            throw new RuntimeException("数据库操作失败", e);
        }
    }

    // 模拟数据库连接类（实现AutoCloseable）
    private static class DatabaseConnection implements AutoCloseable {
        public void transfer(String from, String to, double amount) {
            // 模拟成功操作
            System.out.println("数据库操作成功: 从账户 " + from + " 转账 " + amount + " 到 " + to);
        }

        @Override
        public void close() {
            // 模拟资源清理
            System.out.println("数据库连接已关闭");
        }
    }

    public double getBalance(String account) {
        return accounts.getOrDefault(account, 0.0);
    }
}